package activity.video;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.hichip.callback.ICameraDownloadCallback;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import activity.FishEye.FishPlaybackOnlineActivity;
import activity.LocalFile.LocalFileActivity2;
import activity.WallMounted.WallMountedOnlineActivity;
import activity.video.adapter.VideoOnlineListAdapter;
import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import custom.CircleProgressBar;
import utils.HiToast;
import utils.HiTools;
import utils.SharePreUtils;

/**
 * 远程录像列表 界面
 * Created by lt on 2018\2\27 0027.
 */
public class RemoteRecordingListActivity extends HiActivity implements AdapterView.OnItemClickListener, ICameraIOSessionCallback, ICameraDownloadCallback, View.OnClickListener {
    private View layoutView;
    private MyCamera mCamera;
    private View searchTimeView = null;
    private View loadingView = null;
    //private View noResultView = null;
    private VideoOnlineListAdapter adapter;
    private List<HiChipDefines.HI_P2P_FILE_INFO> file_list = Collections.synchronizedList(new ArrayList<HiChipDefines.HI_P2P_FILE_INFO>());
    private ConnectionChangeReceiver myReceiver;
    private boolean isDownloading = false;
    public final static int HANDLE_MESSAGE_NETWORK_CHANGED = 0x100001;
    // 回调的下载文件路径
    private String path;
    private HiChipDefines.HI_P2P_FILE_INFO evt;
    public final static String SEARCH_ACTIVITY_START_TIME = "START TIME";
    public final static String SEARCH_ACTIVITY_END_TIME = "END TIME";
    public final static String VIDEO_PLAYBACK_START_TIME = "VIDEO START TIME";
    public final static String VIDEO_PLAYBACK_END_TIME = "VIDEO END TIME";
    public final static int SEARCH_ACTIVITY_RESULT = 1;
    private String download_path;
    private String fileName;
    @BindView(R.id.tv_not_online) TextView tv_not_online;

    @BindView(R.id.list_video_online) ListView list_video_online;
    @BindView(R.id.btn_floatingaction) FloatingActionButton btn_floatingaction;
    private int mType = 0;//当前搜索的类型
    private boolean mIsVisible = true;

    @BindView(R.id.btn_return) ImageView btn_return;
    @BindView(R.id.tv_uid) TextView tv_uid;

    @BindView(R.id.tv_nothing) TextView tv_nothing;
    private TextView tv_sort;
    private ImageView iv_arrow;
    private boolean mIsDataReceveEnd=false;//数据是否接受完
    private HiChipDefines.HI_P2P_S_SD_INFO sd_info;


    @Override
    protected int setLayoutId() {
        return R.layout.activity_remote_recording_list;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initView();
        setOnLiserners();
        searchVideo();
    }


    private void getIntentData() {
        String str_uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        if (!TextUtils.isEmpty(str_uid)) {
            for (MyCamera camera : HiDataValue.CameraList) {
                if (str_uid.equals(camera.getUid())) {
                    this.mCamera = camera;
                    break;
                }
            }
        }
    }

    private void setOnLiserners() {
        btn_floatingaction.setOnClickListener(this);
        btn_return.setOnClickListener(this);
        tv_uid.setOnClickListener(this);
    }

    private void initView() {
        tv_uid.setText(mCamera.getUid());
        if (mCamera.getConnectState() != HiCamera.CAMERA_CONNECTION_STATE_LOGIN) {
            list_video_online.setVisibility(View.GONE);
            tv_not_online.setVisibility(View.VISIBLE);
        }
        searchTimeView = getLayoutInflater().inflate(R.layout.search_event_result, null);
        loadingView = getLayoutInflater().inflate(R.layout.loading_events, null);
        //noResultView = getLayoutInflater().inflate(R.layout.no_result, null);
        LinearLayout ll_sort = searchTimeView.findViewById(R.id.ll_sort);
        ll_sort.setOnClickListener(this);
        tv_sort = searchTimeView.findViewById(R.id.tv_sort);
        iv_arrow = searchTimeView.findViewById(R.id.iv_arrow);
    }

    private void searchVideo() {
        long startTime = getBeforeHourTime(6);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        list_video_online.addFooterView(loadingView);

        if (list_video_online.getHeaderViewsCount() == 0) {
            list_video_online.addHeaderView(searchTimeView);
        }

        adapter = new VideoOnlineListAdapter(this, file_list);
        if (mCamera == null || mCamera.getConnectState() != HiCamera.CAMERA_CONNECTION_STATE_LOGIN) {
            //list_video_online.addFooterView(noResultView);
        }
        list_video_online.setAdapter(adapter);
        list_video_online.setOnItemClickListener(this);
        // String timeStr = HiTools.sdfTimeDay(System.currentTimeMillis()) + " -
        // "+ HiTools.sdfTimeSec(System.currentTimeMillis());
        // 改为默认搜索6个小时时间内的录像
        String timeStr = sdf.format(new java.util.Date(startTime)) + " - " + HiTools.sdfTimeSec(System.currentTimeMillis());
        TextView txtSearchTime = (TextView) searchTimeView.findViewById(R.id.txtSearchTimeDuration);
        txtSearchTime.setText(timeStr);
        /*
         * String timeStr= HiTools.sdfTimeDay(System.currentTimeMillis()) +" - "+ HiTools.sdfTimeSec(System.currentTimeMillis()); tv_search_duration.setText(timeStr);
         */
        if (mCamera != null) {
            if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_PB_QUERY_START_NODST)) {
                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START_NODST, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, System.currentTimeMillis(), HiChipDefines.HI_P2P_EVENT_ALL));
            } else if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_PB_QUERY_START_NEW)) {
                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START_NEW, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, System.currentTimeMillis(), HiChipDefines.HI_P2P_EVENT_ALL));
            } else if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_PB_QUERY_START_EXT)) {
                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START_EXT, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, System.currentTimeMillis(), HiChipDefines.HI_P2P_EVENT_ALL));
            } else {
                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, System.currentTimeMillis(), HiChipDefines.HI_P2P_EVENT_ALL));
            }
        }
    }

    /**
     * 获取当前时间制定一个小时之前
     */
    public long getBeforeHourTime(int hour) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - hour);
        return calendar.getTimeInMillis();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 注册
        registerCompent();
        if (mCamera == null) {
            RemoteRecordingListActivity.this.finish();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 解册
        unregisterCompent();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isDownloading = false;
        if (mCamera != null) {
            mCamera.stopDownloadRecording();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);

        }

    }

    private void unregisterCompent() {
        if (mCamera != null) {
            mCamera.unregisterIOSessionListener(this);
            mCamera.unregisterDownloadListener(this);
        }
        if (myReceiver != null) {
            try {
                RemoteRecordingListActivity.this.unregisterReceiver(myReceiver);
            } catch (Exception e) {
            }
        }
    }

    private void registerCompent() {
        if (mCamera != null) {
            mCamera.registerIOSessionListener(this);
            mCamera.registerDownloadListener(this);
        }
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver = new ConnectionChangeReceiver();
        RemoteRecordingListActivity.this.registerReceiver(myReceiver, filter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_floatingaction:
//                if (list_video_online.getChildAt(1) == loadingView) {
//                    return;
//                }
                Intent intent = new Intent(RemoteRecordingListActivity.this, SearchSDCardVideoActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mCamera.getUid());
                startActivityForResult(intent, SEARCH_ACTIVITY_RESULT);
                RemoteRecordingListActivity.this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
                break;
            case R.id.btn_return:
                finish();
                break;
            case R.id.ll_sort://排序
                if(mIsDataReceveEnd){
                    if (tv_sort == null) return;
                    if (iv_arrow == null) return;
                    tv_sort.setText(mIsDown ? getString(R.string.asce) : getString(R.string.desc));
                    iv_arrow.animate().rotation(mIsDown ? 180f : 0f).setDuration(400).start();
                        Collections.reverse(file_list);
                        adapter.notifyDataSetChanged();
                    mIsDown = !mIsDown;
                }else {
                    HiToast.showToast(this,getString(R.string.data_get_wait));
                }
                break;
        }

    }

    private boolean mIsDown = true;//true 就是降序  false 就是升序


    public class ConnectionChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

            if (mobNetInfo != null && !mobNetInfo.isConnected() && wifiNetInfo != null && !wifiNetInfo.isConnected()) {
                if (isDownloading) {
                    handler.sendEmptyMessage(HANDLE_MESSAGE_NETWORK_CHANGED);
                }
            } else {

            }
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        popupMethod(position);
    }

    private void popupMethod(int position) {
        final int pos = position - list_video_online.getHeaderViewsCount();
        if (pos < 0) return;
        View customView = View.inflate(RemoteRecordingListActivity.this, R.layout.popview_video_online, null);
        PopupWindow pup = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        pup.setBackgroundDrawable(cd);
        pup.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        pup.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        pup.setFocusable(true);
        pup.showAtLocation(customView, Gravity.CENTER, 0, 0);

        evt = file_list.get(pos);
        TextView tvState = (TextView) customView.findViewById(R.id.pup_vo_item_tv_state);
        final String[] mTextArray = getResources().getStringArray(R.array.online_recording_type);
        if (evt.EventType <= 3 && evt.EventType >= 0) {
            tvState.setText(mTextArray[evt.EventType]);
        }
        TextView tvTime = (TextView) customView.findViewById(R.id.pup_vo_item_tv_time);
        String[] strings1 = evt.sStartTime.toString().split(" ");
        String[] strings2 = evt.sEndTime.toString().split(" ");
        tvTime.setText(strings1[0] + "   " + strings1[1] + " - " + strings2[1]);

        // 1.回放
        TextView tvPlay = customView.findViewById(R.id.tv_play_video_online);
        tvPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pup.dismiss();
                playbackRecording(pos);
            }
        });

        TextView tvDownLoad = customView.findViewById(R.id.tv_downlinad_video_online);
        // 2.下载
        tvDownLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pup.dismiss();
                // 检查存储权限
                if (HiTools.checkPermission(RemoteRecordingListActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    downloadRecording(pos, evt);
                } else {
                    ActivityCompat.requestPermissions(RemoteRecordingListActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
                }
            }
        });
        TextView tvCance = customView.findViewById(R.id.tv_downlinad_video_cancel);
        // 3.取消
        tvCance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pup.dismiss();
            }
        });
    }

    private void playbackRecording(int position) {
        if (mCamera == null) return;
        HiChipDefines.HI_P2P_FILE_INFO file_info = file_list.get(position);
        Bundle extras = new Bundle();
        extras.putString(HiDataValue.EXTRAS_KEY_UID, mCamera.getUid());
        byte[] b_startTime = file_info.sStartTime.parseContent();
        extras.putByteArray("st", b_startTime);

        long startTimeLong = file_info.sStartTime.getTimeInMillis2();
        long endTimeLong = file_info.sEndTime.getTimeInMillis2();
        extras.putLong(VIDEO_PLAYBACK_START_TIME, startTimeLong);
        extras.putLong(VIDEO_PLAYBACK_END_TIME, endTimeLong);

        String[] strings = file_info.sEndTime.toString().split(" ");
        String[] strings2 = file_info.sStartTime.toString().split(" ");
        String str = strings2[0] + "   " + strings2[1] + "-" + strings[1];
        extras.putString("title", str);

        Intent intent = new Intent();
        intent.putExtras(extras);

        if (mCamera.isWallMounted) {
            intent.setClass(RemoteRecordingListActivity.this, WallMountedOnlineActivity.class);
            startActivity(intent);
            return;
        }

        if (mCamera.isFishEye()) {
            intent.setClass(RemoteRecordingListActivity.this, FishPlaybackOnlineActivity.class);
        } else {
            intent.setClass(RemoteRecordingListActivity.this, PlaybackOnlineActivity.class);
        }
        startActivity(intent);
    }

    private void downloadRecording(int position, final HiChipDefines.HI_P2P_FILE_INFO file_infos) {
        if (HiTools.isSDCardValid()) {
            File file_dir = new File(HiDataValue.getPathCameraVideoOnLineDownLoad(mCamera.getUid(),this));
            if (!file_dir.exists()) {
                file_dir.mkdirs();
            }
            download_path = file_dir.getAbsoluteFile() + "/";
            // 创建UID文件夹
            fileName = splitFileName(file_infos.sStartTime.toString());
            File file = new File(download_path + fileName + ".avi");
            File file2 = new File(download_path + fileName + ".mp4");
            File file3 = new File(download_path + fileName + ".h264");

            if (file.exists() || file2.exists() || file3.exists()) {// 文件已下载过
                View view = View.inflate(RemoteRecordingListActivity.this, R.layout.popuwindow_aleary_down, null);
                PopupWindow popupWindow = new PopupWindow(view);
                ColorDrawable cd = new ColorDrawable(-000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setFocusable(true);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

                TextView item_tv_know = view.findViewById(R.id.item_tv_know);
                item_tv_know.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                return;
            }
            new Thread() {
                public void run() {
                    // 默认都下载264的文件(如果是文件本身是avi 则还是avi格式,如果是其他格式则变成264格式)
                    mCamera.startDownloadRecording2(file_infos.sStartTime, download_path, fileName, 2);
                }
            }.start();
        } else {
            Toast.makeText(RemoteRecordingListActivity.this, getText(R.string.tips_no_sdcard).toString(), Toast.LENGTH_SHORT).show();
        }
    }


    private String splitFileName(String str) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long time = 0;
        try {
            time = sdf.parse(str).getTime();
        } catch (ParseException e) {

            e.printStackTrace();
        }

        SimpleDateFormat sf2 = new SimpleDateFormat("yyyyMMdd_HHmmss");

        return sf2.format(time);
    }


    @Override
    public void receiveSessionState(HiCamera arg0, int arg1) {
        Message msg = handler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_SESSION_STATE;
        msg.arg1 = arg1;
        msg.obj = arg0;
        handler.sendMessage(msg);
    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = handler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        handler.sendMessage(msg);
    }

    @Override
    public void callbackDownloadState(HiCamera camera, int total, int curSize, int state, String path) {
        if (camera != mCamera) return;
        Bundle bundle = new Bundle();
        bundle.putLong("total", total);
        bundle.putLong("curSize", curSize);
        bundle.putString("path", path);

        Message msg = handler.obtainMessage();
        msg.what = HiDataValue.HANDLE_MESSAGE_DOWNLOAD_STATE;
        msg.arg1 = state;
        msg.setData(bundle);
        handler.sendMessage(msg);

    }

    private void handNETWORK_CHANGED() {
        if (!isDownloading) {
            return;
        }
        isDownloading = false;
        if (mCamera != null) {
            mCamera.stopDownloadRecording();
        }
        HiToast.showToast(RemoteRecordingListActivity.this, getString(R.string.tips_network_disconnect));
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLE_MESSAGE_NETWORK_CHANGED:
                    handNETWORK_CHANGED();
                    break;
                case HiDataValue.HANDLE_MESSAGE_SESSION_STATE:
                    switch (msg.arg1) {
                        case HiCamera.CAMERA_CONNECTION_STATE_DISCONNECTED:
                            if (isDownloading) {
                                if (!TextUtils.isEmpty(path)) {
                                    File file = new File(path);
                                    if (file != null && file.isFile() && file.exists()) {
                                        file.delete();
                                    }
                                }
                            }
                            dismissjuHuaDialog();
                            if (mIsVisible) {
                                HiToast.showToast(RemoteRecordingListActivity.this, getString(R.string.disconnect));
                                RemoteRecordingListActivity.this.finish();
                            }
                            break;
                    }
                    break;
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == -1) {// IO的错误码
                        HiToast.showToast(RemoteRecordingListActivity.this, getString(R.string.tips_update_system_failed));
                        return;
                    }
                    if (msg.arg2 == 0) {
                        Bundle bundle = msg.getData();
                        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
                        switch (msg.arg1) {
                            case HiChipDefines.HI_P2P_GET_SD_INFO:
                                sd_info = new HiChipDefines.HI_P2P_S_SD_INFO(data);
                                boolean mIsHaveSDCard = sd_info.u32Status == 1 ? true : false;

                                list_video_online.removeHeaderView(searchTimeView);
                                list_video_online.setVisibility(View.GONE);
                                tv_nothing.setVisibility(View.VISIBLE);

                                String str = " ";
                                switch (mType) {
                                    case 0://默认
                                        str ="<font color='#45A7E6'>"+getString(R.string.six_hours)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                    case 1://一个小时
                                        str ="<font color='#45A7E6'>"+getString(R.string.one_hours)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                    case 2://半天
                                        str = "<font color='#45A7E6'>"+getString(R.string.half_day)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                    case 3://一天
                                        str = "<font color='#45A7E6'>"+getString(R.string.one_day)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                    case 4://一周
                                        str = "<font color='#45A7E6'>"+getString(R.string.one_week)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                    case 5://自定义
                                        str = "<font color='#45A7E6'>"+getString(R.string.constom_time)+"</font><font color='#666666'/>"+getString(R.string.click_right_corner)+"</font>";
                                        break;
                                }
                                if(!mIsHaveSDCard){
                                    str=getString(R.string.no_sdcard);
                                }
                                tv_nothing.setText(Html.fromHtml(str));
                                break;
                            case HiChipDefines.HI_P2P_START_REC_UPLOAD_EXT:// 下载
                                break;
                            case HiChipDefines.HI_P2P_PB_QUERY_START_NODST:
                            case HiChipDefines.HI_P2P_PB_QUERY_START:
                                if (data.length >= 12) {
                                    byte flag = data[8];// 数据发送的结束标识符
                                    int cnt = data[9]; // 当前包的文件个数
                                    if (cnt > 0) {
                                        for (int i = 0; i < cnt; i++) {
                                            int pos = 12;
                                            int size = HiChipDefines.HI_P2P_FILE_INFO.sizeof();
                                            byte[] t = new byte[24];
                                            if (data.length >= i * size + pos + 24) {
                                                System.arraycopy(data, i * size + pos, t, 0, 24);
                                                HiChipDefines.HI_P2P_FILE_INFO file_info = new HiChipDefines.HI_P2P_FILE_INFO(t);
                                                long duration = file_info.sEndTime.getTimeInMillis() - file_info.sStartTime.getTimeInMillis();
                                                if (duration <= 1000 * 1000 && duration > 0) { // 1000秒，文件录像一般为15分钟，但是有可能会长一点所有就设置为1000
                                                    file_list.add(file_info);
                                                }
                                            }
                                        }
                                    }
                                    if (flag == 1) {// 表示数据收完了
                                        mIsDataReceveEnd=true;
                                        list_video_online.removeFooterView(loadingView);
                                        if (file_list != null && file_list.size() <= 0) {
                                            //发送命令获取是否有SD卡
                                            if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_GET_SD_INFO)) {
                                                mCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_SD_INFO, new byte[0]);
                                            }
                                        }
                                        dismissjuHuaDialog();
                                        Collections.reverse(file_list);
                                        adapter.notifyDataSetChanged();
                                    }
                                }
                                break;
                        }
                    }
                    break;
                case HiDataValue.HANDLE_MESSAGE_DOWNLOAD_STATE:
                    handDownLoad(msg);
                    break;
            }
        }
    };

    private void handDownLoad(Message msg) {
        Bundle bundle = msg.getData();
        switch (msg.arg1) {
            case DOWNLOAD_STATE_START:
                showPopPupProgress();
                isDownloading = true;
                path = bundle.getString("path");
                break;
            case DOWNLOAD_STATE_DOWNLOADING:
                if (isDownloading == false) return;
                float d;
                long total = bundle.getLong("total");
                if (total == 0) {
                    d = bundle.getLong("curSize") * 100 / (1024 * 1024);
                } else {
                    d = bundle.getLong("curSize") * 100 / total;
                }
                if (d >= 100) {
                    d = 99;
                }
                int rate = (int) d;
                if (circleprogressbar != null) {
                    circleprogressbar.setProgress(rate);
                }
                break;
            case DOWNLOAD_STATE_END:
                SharePreUtils.putInt("cache", RemoteRecordingListActivity.this, fileName, evt.EventType);
                if (circleprogressbar != null) {
                    circleprogressbar.setProgress(100);
                }
                isDownloading = false;
                if (tv_cancel_downloading_video != null) {
                    tv_cancel_downloading_video.setText(R.string.continue_down);
                }
                if (tv_goto_downloading_video != null) {
                    tv_goto_downloading_video.setVisibility(View.VISIBLE);
                }
                if (popu_tips_down != null) {
                    popu_tips_down.setText(getString(R.string.download_done));
                }
                circleprogressbar.setVisibility(View.GONE);
                tv_one.setVisibility(View.VISIBLE);
                tv_two.setVisibility(View.VISIBLE);

                ObjectAnimator animator = ObjectAnimator.ofFloat(tv_one, "Alpha", 0f, 1f);
                animator.setDuration(300);
                animator.start();

                ObjectAnimator animator1 = ObjectAnimator.ofFloat(tv_two, "Alpha", 0f, 1f);
                animator1.setDuration(300);
                animator1.start();
                break;
            case DOWNLOAD_STATE_ERROR_PATH:
                HiToast.showToast(RemoteRecordingListActivity.this, getString(R.string.tips_wifi_connect_failed));
                break;
            case DOWNLOAD_STATE_ERROR_DATA:
                if (mCamera != null && isDownloading) {
                    mCamera.stopDownloadRecording();
                    isDownloading = false;
                    mCamera.disconnect();
                    mCamera.connect();
                }
                break;

        }
    }

    private CircleProgressBar circleprogressbar;
    private TextView tv_cancel_downloading_video;
    private TextView tv_goto_downloading_video;
    private TextView popu_tips_down;
    private TextView tv_one, tv_two;

    private void showPopPupProgress() {
        View customView = getLayoutInflater().inflate(R.layout.pup_loading_video, null, false);
        PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);
        circleprogressbar = customView.findViewById(R.id.circleprogressbar);
        popu_tips_down = customView.findViewById(R.id.popu_tips_down);
        tv_one = customView.findViewById(R.id.tv_one);
        tv_two = customView.findViewById(R.id.tv_two);

        final String[] mTextArray = getResources().getStringArray(R.array.online_recording_type);
        if (evt.EventType <= 3 && evt.EventType >= 0) {
            popu_tips_down.setText(mTextArray[evt.EventType]);
        }
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isDownloading = false;
                if (mCamera != null) {
                    mCamera.stopDownloadRecording();
                }
            }
        });


        //取消和继续下载
        tv_cancel_downloading_video = customView.findViewById(R.id.tv_cancel_downloading_video);
        tv_cancel_downloading_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getString(R.string.continue_down).equals(tv_cancel_downloading_video.getText().toString().trim())) {//继续下载
                    popupWindow.dismiss();
                } else {//取消
                    popupWindow.dismiss();
                    deleteLoadingFile();
                }
            }
        });

        //前往查看
        tv_goto_downloading_video = customView.findViewById(R.id.tv_goto_downloading_video);
        tv_goto_downloading_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                //要跳转到本地录像
                Intent intent = new Intent(RemoteRecordingListActivity.this, LocalFileActivity2.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mCamera.getUid());
                startActivity(intent);
            }
        });
    }


    private void deleteLoadingFile() {
        File file = new File(path);
        file.delete();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (resultCode == Activity.RESULT_OK) {
            tv_sort.setText(getString(R.string.desc));
            mIsDown=true;
            iv_arrow.animate().rotation(0f).setDuration(0).start();
            Bundle bundle = intent.getBundleExtra(HiDataValue.EXTRAS_KEY_DATA);
            long startTime = bundle.getLong(SEARCH_ACTIVITY_START_TIME);
            long endTime = bundle.getLong(SEARCH_ACTIVITY_END_TIME);
            mType = intent.getIntExtra("type", 5);
            file_list.clear();
            if (mCamera != null) {
                mIsDataReceveEnd=false;
                if (mCamera.getCommandFunction(HiChipDefines.HI_P2P_PB_QUERY_START_NODST)) {
                    mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START_NODST, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, endTime, HiChipDefines.HI_P2P_EVENT_ALL));
                } else {
                    mCamera.sendIOCtrl(HiChipDefines.HI_P2P_PB_QUERY_START, HiChipDefines.HI_P2P_S_PB_LIST_REQ.parseContent(0, startTime, endTime, HiChipDefines.HI_P2P_EVENT_ALL));
                }
            }

            list_video_online.setVisibility(View.VISIBLE);
            tv_nothing.setVisibility(View.GONE);

            if (list_video_online.getHeaderViewsCount() == 0) {
                list_video_online.addHeaderView(searchTimeView);
            }
            if (list_video_online.getFooterViewsCount() == 0) {
                list_video_online.addFooterView(loadingView);
            }
            adapter.notifyDataSetChanged();
            String timeStr = HiTools.sdfTimeSec(startTime) + " - " + HiTools.sdfTimeSec(endTime);
            TextView txtSearchTime = (TextView) searchTimeView.findViewById(R.id.txtSearchTimeDuration);
            txtSearchTime.setText(timeStr);
            mCamera.registerIOSessionListener(this);
        }
    }


}
